package com.hh.xx.hive;

import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hive.service.auth.PlainSaslHelper;
import org.apache.hive.service.cli.OperationHandle;
import org.apache.hive.service.cli.RowSet;
import org.apache.hive.service.cli.SessionHandle;
import org.apache.hive.service.cli.thrift.ThriftCLIServiceClient;
import org.apache.hive.service.rpc.thrift.TCLIService;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

import java.util.Arrays;

/**
 *
 */
public class HiveCliClient {
    protected static String USERNAME = "anonymous";
    protected static String PASSWORD = "anonymous";

    public static void main(String[] args) throws Exception {
        HiveConf hiveConf = new HiveConf();
        hiveConf.addResource("/Users/tzp/Documents/env/apache-hive-3.1.2-bin/conf/hive-site.xml");

        TTransport transport = new TSocket("127.0.0.1", 10000);
        transport = PlainSaslHelper.getPlainTransport(USERNAME, PASSWORD, transport);
        TBinaryProtocol protocol = new TBinaryProtocol(transport);
        transport.open();

        ThriftCLIServiceClient cliServiceClient = new ThriftCLIServiceClient(new TCLIService.Client(protocol), hiveConf);

        SessionHandle sessionHandle = cliServiceClient.openSession(USERNAME, PASSWORD);

        OperationHandle operationHandle = cliServiceClient.executeStatement(sessionHandle, "select * from u_data_ex limit 2", null);

        RowSet results = cliServiceClient.fetchResults(operationHandle);

        for (Object[] result : results) {
            System.out.println(Arrays.asList(result));
        }

    }

}